'''
Author: thinktanker thinktanker@163.com
Date: 2024-03-04 14:37:54   
LastEditors: duliang thinktanker@163.com
LastEditTime: 2025-09-23 08:45:46
FilePath: 
Description: '''
import socket
import threading
import subprocess
# from multiprocessing import Process
import re
import json
import os
from mywechat import *
# import getsq, swpng
from getsq import getzhakg
from myconfig import *

# wxid_list = ['wxid_1989279891512']
os.system("title 微信机器人")
local_path = os.path.abspath(os.curdir)


class wechatServer():

    def __init__(self, port) -> None:
        self.port = port
        self.w = wechat()
        self.ID_list = swid_list

    def short_msg(self, msg):
        """短消息"""
        data = re.findall(r'({.*?"wxid".*?})', msg)
        Sender = ''
        StrTalker = ''
        StrContent = ''
        MsgSvrID = ''
        BytesExtra = ''
        if data:
            data = data[0]
            j = json.loads(data)
            mydict = j["data"][0]
            if mydict:
                StrTalker = j["data"][0]["StrTalker"]
                StrTalker = mydict.get("StrTalker")
                StrContent = mydict.get("StrContent")
                Sender = mydict.get("Sender")
                MsgSvrID = mydict.get("MsgSvrID")
                BytesExtra = mydict.get("BytesExtra")
                # if "StrContent" in j["data"][0]:
                #     StrContent = j["data"][0]["StrContent"]
                # if "Sender" in j["data"][0]:
                #     Sender = j["data"][0]["Sender"]
                # if "MsgSvrID" in j["data"][0]:
                #     MsgSvrID = j["data"][0]["MsgSvrID"]
                # if "BytesExtra" in j["data"][0]:
                #     BytesExtra = j["data"][0]["BytesExtra"]
        return Sender, StrTalker, StrContent, MsgSvrID, BytesExtra

    def handle_data(self, recv_data, address):
        """回调函数，处理接收到的数据"""
        # print(f"Received from {address}: {recv_data}")
        Sender, StrTalker, StrContent, MsgSvrID, BytesExtra = self.short_msg(
            recv_data)
        messages = ''
        # print("bytes:", BytesExtra)
        StrTalker_name = StrTalker
        if not StrContent:
            print(recv_data)

        if Sender:
            if re.findall(r"<msgsource>.*?</msgsource>", Sender):
                NickName = "我"
                Sender = "wxid_1989279891512"
            else:
                NickName = self.w.get_dbaccountbywxid(Sender)
            StrTalker_name = self.w.get_dbaccountbywxid(StrTalker)
            messages = f'群：{StrTalker_name}({StrTalker})->{NickName}({Sender})<- --> {StrContent}  ↑→{MsgSvrID}'
            # 初一（22）家校群
            if StrTalker == "55889703003@chatroom":
                if Sender in teacher_wxid_list:
                    if BytesExtra:
                        self.w.forward_img("wxid_1989279891512",
                                           "18869310340@chatroom", BytesExtra)
                    if StrContent:
                        self.w.sendTextMsg("18869310340@chatroom",
                                           NickName + "->" + StrContent)
                    elif not re.findall(r'.*?<img.*?/>', recv_data):
                        if MsgSvrID:
                            self.w.forward_msg("18869310340@chatroom",
                                               MsgSvrID)
                    # if MsgSvrID:
                    #     self.w.forward_msg("18869310340@chatroom", MsgSvrID)
            # 测试3群
            # 我的信息都转到 文件传输助手
            elif StrTalker == "9185274267@chatroom":
                # if Sender == "wxid_1989279891512":
                # self.w.sendTextMsg("9185274267@chatroom", NickName)
                if BytesExtra:
                    self.w.forward_img("wxid_1989279891512", "filehelper",
                                       BytesExtra)
                if StrContent:
                    self.w.sendTextMsg("filehelper",
                                       str(NickName) + "->" + StrContent)
                    # '调度',1755393364,'1755393364&我&二次测试','首页调令'
                    self.w.sendSQToServer(
                        f"[{int(time.time())},{NickName},{StrContent}]")

                elif not re.findall(r'.*?<img.*?/>', recv_data):
                    if MsgSvrID:
                        self.w.forward_msg("filehelper", MsgSvrID)
            # lysq 骆运水情
            # 全部转发到测试1群
            elif StrTalker == "25220292807@chatroom":
                if BytesExtra:
                    self.w.forward_img("wxid_1989279891512",
                                       "39168791654@chatroom", BytesExtra)
                if StrContent:
                    self.w.sendTextMsg("39168791654@chatroom",
                                       NickName + "->" + StrContent)
                    # self.w.sendSQToServer(NickName + "&" + StrContent + "&" + ())
                    self.w.sendSQToServer(
                        f"[{int(time.time())},{NickName},{StrContent}]")

                    if MsgSvrID:
                        self.w.forward_msg("39168791654@chatroom", MsgSvrID)

            # 就餐群点名
            elif StrTalker == "19460744006@chatroom":
                if StrContent:
                    # self.w.sendTextMsg("filehelper",
                    #                    str(NickName) + "->" + StrContent)
                    self.w.send_server(str(NickName), StrContent)
                    # if "晚" in StrContent:
                    #     self.w.sendTextMsg("19460744006@chatroom",
                    #                        "@" + Sender + " " + StrContent)
                    # elif "早" in StrContent:
                    #     self.w.sendTextMsg("19460744006@chatroom",
                    #                        "@" + Sender + " " + StrContent)
                    # elif "中" in StrContent:
                    #     self.w.sendTextMsg("19460744006@chatroom",
                    #                        "@" + Sender + " " + StrContent)
        else:
            NickName = self.w.get_dbaccountbywxid(StrTalker)
            messages = f'私：->{NickName}({StrTalker})<- --> {StrContent}  ↑→{MsgSvrID}'
        print(messages)

        # 测试1群
        if StrTalker_name == "测试1群" or StrTalker_name == "filehelper":
            if StrContent == "水位":
                threading.Thread(target=self.w.get_sw,
                                 args=(StrTalker, )).start()
            elif "趋势" == StrContent:
                threading.Thread(target=self.w.get_qs,
                                 args=(StrTalker, )).start()
            elif "一站" == StrContent:
                threading.Thread(target=self.w.get_1zhan,
                                 args=(StrTalker, )).start()
            elif "二站" == StrContent:
                threading.Thread(target=self.w.get_2zhan,
                                 args=(StrTalker, )).start()
            elif re.findall(r".*?闸 \d+ \d+", StrContent):
                threading.Thread(target=self.w.get_sw,
                                 args=(StrTalker, )).start()
                zhaStr_list = re.findall(r"闸 (\d+) (\d+)", StrContent)
                kgstr = getzhakg(zhaDetail=StrContent,
                                 liuliang=zhaStr_list[0][0],
                                 zhakong=zhaStr_list[0][1],
                                 zhakuan=10,
                                 xishu=3.98,
                                 xishuE=1.1)
                self.w.sendTextMsg(StrTalker, kgstr)
            elif "能源" == StrContent:
                threading.Thread(target=self.w.get_nysw,
                                 args=(StrTalker, )).start()

    def start_server(self):
        """启动服务器，监听指定端口，并在接收到数据时调用回调函数"""
        print("启动服务")
        # callback = self.handle_data
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind(('localhost', self.port))  # 绑定本地IP和端口
        server_socket.listen(1)  # 开始监听，允许的最大连接数为1
        print(f"运行在{self.port}")
        while True:
            client_socket, address = server_socket.accept()  # 接受客户端连接
            received_data = client_socket.recv(8196).decode('utf-8')
            # 关闭客户端连接
            client_socket.close()
            # print(f"Connection established with {address}")
            # 创建一个新的线程来处理客户端的连接和数据接收
            # 这样主线程可以继续监听新的连接
            threading.Thread(target=self.handle_data,
                             args=(received_data, address)).start()


def start_exe():
    """启动外部程序"""
    # exe_path = './bin/wxbot-sidecar.exe'
    process = subprocess.Popen(
        [f'{os.path.dirname(__file__)}/bin/wxbot-sidecar.exe'])
    # os.system(f'{os.path.dirname(__file__)}/bin/wxbot-sidecar.exe')
    process.wait()
    # 若需要获取程序的标准输出（stdout）或标准错误输出（stderr），可以设置管道
    # stdout_output = subprocess.check_output([], text=True)
    # print(stdout_output)
    # 如果你希望同时获取stdout和stderr，并且它们混在一起，则可以如下操作：
    # combined_output = subprocess.run([exe_path], capture_output=True, text=True)
    # print(combined_output.stdout)


def handle_data(received_data, address):
    """回调函数，处理接收到的数据"""
    print(f"Received from {address}: {received_data}")
    data = re.findall(r'({.*?"wxid".*?})', received_data)
    if data:
        data = data[0]
        j = json.loads(data)
        StrTalker = j["data"][0]["StrTalker"]
        StrContent = j["data"][0]["StrContent"]
        if StrTalker in []:
            print(f"Received from {address}: {StrContent}")
        print(j["data"][0]["StrTalker"])
        print(j["data"][0]["StrContent"])


def start_server(port, callback=handle_data):
    """启动服务器，监听指定端口，并在接收到数据时调用回调函数"""
    print("启动服务")
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind(('localhost', port))  # 绑定本地IP和端口
    server_socket.listen(5)  # 开始监听，允许的最大连接数为1

    while True:
        client_socket, address = server_socket.accept()  # 接受客户端连接
        # received_data = b''
        # while True:
        #     chunk = client_socket.recv(64)
        #     if not chunk:
        #         break
        #     received_data += chunk
        #     # print(received_data)
        received_data = client_socket.recv(4096)
        received_data = received_data.decode('utf-8')
        print(received_data)
        # 关闭客户端连接
        client_socket.close()
        print(f"Connection established with {address}")
        # 创建一个新的线程来处理客户端的连接和数据接收
        # 这样主线程可以继续监听新的连接
        threading.Thread(target=callback,
                         args=(received_data, address)).start()


def start():
    w = wechatServer(8083)
    w.start_server()


# 使用示例
if __name__ == "__main__":
    # p1 = Process(target=start)
    # p1.start()
    # # p = Process(target=start_exe)
    # # p.start()
    # # p.join()
    # p1.join()
    start()
    print("what?")
    # start_exe()

    #
    # 'POST /callback HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: 1442\r\n\r\n{"data":[{"BytesExtra":"GjYIBxIyPG1zZ3NvdXJjZT48YWxub2RlPjxjZj4zPC9jZj48L2Fsbm9kZT48L21zZ3NvdXJjZT4aJAgCEiBlMWI3MDBmNzMyMjYzZTI5NGUyYjJhNzg2ODI5NmE0Ng==","BytesTrans":"","CompressContent":"","CreateTime":"1709548661","DisplayContent":"","FlagEx":"0","IsSender":"1","MsgSequence":"863578340","MsgServerSeq":"0","MsgSvrID":"0","Reserved0":"0","Reserved1":"1","Reserved2":"","Reserved3":"","Reserved4":"","Reserved5":"","Reserved6":"","Sender":"<msgsource><alnode><cf>3</cf></alnode></msgsource>","Sequence":"1709548661000","Status":"1","StatusEx":"0","StrContent":"{\\"data\\":[{\\"BytesExtra\\":\\"GjYIBxIyPG1zZ3NvdXJjZT48YWxub2RlPjxjZj4zPC9jZj48L2Fsbm9kZT48L21zZ3NvdXJjZT4aJAgCEiAxMmI3MzEzNGI0OWU2YTUwOTk1ODk1MjEzYWIyOGUyNQ==\\",\\"BytesTrans\\":\\"\\",\\"CompressContent\\":\\"\\",\\"CreateTime\\":\\"1709548618\\",\\"DisplayContent\\":\\"\\",\\"FlagEx\\":\\"0\\",\\"IsSender\\":\\"1\\",\\"MsgSequence\\":\\"863578321\\",\\"MsgServerSeq\\":\\"0\\",\\"MsgSvrID\\":\\"'
